package xyz.zhouxf.rpc.serializer.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import xyz.zhouxf.rpc.entity.RpcRequest;
import xyz.zhouxf.rpc.entity.RpcResponse;
import xyz.zhouxf.rpc.enumeration.SerializerCode;
import xyz.zhouxf.rpc.serializer.RpcSerializer;

/**
 * @author zhouxf
 * @date 2022/8/20
 */
@Slf4j
public class JsonSerializer implements RpcSerializer {

    @Override
    public <T> byte[] serialize(T object) {
        try {
            return JSON.toJSONBytes(object);
        } catch (Exception e) {
            log.error("序列化错误：{}",e.getMessage());
            e.printStackTrace();
            return null;
        }

    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clazz) {
        try {
            T obj = JSON.parseObject(bytes,clazz);
            handleRequest(obj);
            return obj;
        } catch (Exception e) {
            log.error("反序列化错误：{}",e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 处理request请求中调用方法参数的JSON反序列化
     * @param object 需要处理的对象
     */
    private void handleRequest(Object object) {
        if(object instanceof RpcResponse) {
            return;
        }
        RpcRequest request = (RpcRequest) object;
        for(int i = 0;i < request.getParams().length;i++) {
            byte[] bytes = JSON.toJSONBytes(request.getParams()[i]);
            request.getParams()[i] = JSON.parseObject(bytes, request.getParamTypes()[i]);
        }
        //return request;
    }

    @Override
    public byte getCode() {
        return SerializerCode.JSON.getCode();
    }

}
